/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmConfiguracion.java
 *
 * Created on 04-sep-2011, 3:14:41
 */

package GUI;

import BaseDatos.GestorBD;
import Util.GestorConfiguracion;
import Util.GestorErrores;
import Util.Varios;
import javax.swing.JOptionPane;

/**
 *
 * @author Javi
 */
public class frmConfiguracion extends javax.swing.JDialog {

    /** Creates new form frmConfiguracion */
    public frmConfiguracion(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        getRootPane().setDefaultButton(jButtonCancelar);
    }

    public void inicializaFormulario ( char cOperacion ){
        this.setTitle( GestorConfiguracion.getInstancia().getsDescripTabla() + " - " + Varios.getLiteralOperacion(cOperacion) );
        //Carga los datos de la clase
        this.claseAPantalla();
    }

    /*
     * Este método carga los atributos de la clase en los controles del formulario de entrada.
     */
    private void claseAPantalla(){
        //Umbrales morosidad
        this.jFTFMinDenegAuto.setValue( Integer.parseInt(GestorConfiguracion.getInstancia().getProperty(GestorConfiguracion.MIN_DENEGA_AUTO)) );
        this.jFTFMaxAutorizAuto.setValue( Integer.parseInt(GestorConfiguracion.getInstancia().getProperty(GestorConfiguracion.MAX_AUTORIZ_AUTO)) );
        //Base de datos
        this.jTFNombreBD.setText ( GestorConfiguracion.getInstancia().getProperty(GestorConfiguracion.BASE_DATOS) );
        this.jTFHost.setText( GestorConfiguracion.getInstancia().getProperty(GestorConfiguracion.HOST_BD) );
        this.jFTFPuerto.setValue( Integer.parseInt(GestorConfiguracion.getInstancia().getProperty(GestorConfiguracion.PUERTO_BD)) );
        this.jTFUsuario.setText( GestorConfiguracion.getInstancia().getProperty(GestorConfiguracion.USUARIO_BD) );
        this.jTFPassword.setText( GestorConfiguracion.getInstancia().getProperty(GestorConfiguracion.PASSWORD_BD) );
    }

    /*
     * Este método captura los datos introducidos por el usuario y los carga en los atributos
     * correspondientes de la clase.
     */
    private void pantallaAClase(){
        //Umbrales morosidad
        GestorConfiguracion.getInstancia().setProperty(GestorConfiguracion.MIN_DENEGA_AUTO, ((Integer) this.jFTFMinDenegAuto.getValue()).toString() );
        GestorConfiguracion.getInstancia().setProperty(GestorConfiguracion.MAX_AUTORIZ_AUTO, ((Integer) this.jFTFMaxAutorizAuto.getValue()).toString() );
        //Base de datos
        GestorConfiguracion.getInstancia().setProperty(GestorConfiguracion.BASE_DATOS,this.jTFNombreBD.getText().trim() );
        GestorConfiguracion.getInstancia().setProperty(GestorConfiguracion.HOST_BD, this.jTFHost.getText().trim());
        GestorConfiguracion.getInstancia().setProperty(GestorConfiguracion.PUERTO_BD, ((Integer) this.jFTFPuerto.getValue()).toString() );
        GestorConfiguracion.getInstancia().setProperty(GestorConfiguracion.USUARIO_BD, this.jTFUsuario.getText().trim() );
        GestorConfiguracion.getInstancia().setProperty(GestorConfiguracion.PASSWORD_BD, this.jTFPassword.getText().trim() );
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jFTFMaxAutorizAuto = new javax.swing.JFormattedTextField(new Integer(0));
        jLabel7 = new javax.swing.JLabel();
        jFTFMinDenegAuto = new javax.swing.JFormattedTextField(new Integer(0));
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTFHost = new javax.swing.JTextField();
        jTFUsuario = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTFPassword = new javax.swing.JTextField();
        jButtonTestConexion = new javax.swing.JButton();
        jFTFPuerto = new javax.swing.JFormattedTextField(new Integer(0));
        jTFNombreBD = new javax.swing.JTextField();
        jButtonAceptar = new javax.swing.JButton();
        jButtonCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jLabel6.setText("Umbral Máx. autorización automática solicitudes de préstamo (%) ");

        jFTFMaxAutorizAuto.setColumns(6);
        jFTFMaxAutorizAuto.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        jLabel7.setText("Umbral Mín. de denegación automática solicitudes de préstamo (%)");

        jFTFMinDenegAuto.setColumns(6);
        jFTFMinDenegAuto.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jFTFMaxAutorizAuto, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addGap(18, 18, 18)
                        .addComponent(jFTFMinDenegAuto, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(174, 174, 174))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(64, 64, 64)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jFTFMinDenegAuto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(24, 24, 24)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jFTFMaxAutorizAuto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(109, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Umbrales morosidad", jPanel2);

        jLabel1.setText("Nombre de la Base de datos");

        jLabel2.setText("Nombre del Host");

        jLabel3.setText("Puerto");

        jLabel4.setText("Usuario");

        jTFHost.setColumns(15);

        jTFUsuario.setColumns(15);

        jLabel5.setText("Contraseña");

        jTFPassword.setColumns(15);

        jButtonTestConexion.setText("Probar conexión");
        jButtonTestConexion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonTestConexionActionPerformed(evt);
            }
        });

        jFTFPuerto.setColumns(6);
        jFTFPuerto.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        jTFNombreBD.setColumns(15);
        jTFNombreBD.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel5)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jTFHost, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jTFUsuario, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jTFPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jFTFPuerto, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jTFNombreBD, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(55, 55, 55)
                .addComponent(jButtonTestConexion)
                .addGap(246, 246, 246))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(93, 93, 93)
                        .addComponent(jButtonTestConexion))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jTFNombreBD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jTFHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3)
                            .addComponent(jFTFPuerto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(jTFUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(jTFPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(36, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Base de Datos", jPanel1);

        jButtonAceptar.setText("Aceptar");
        jButtonAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAceptarActionPerformed(evt);
            }
        });

        jButtonCancelar.setText("Cancelar");
        jButtonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(162, 162, 162)
                        .addComponent(jButtonAceptar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonCancelar))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 518, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 271, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonCancelar)
                    .addComponent(jButtonAceptar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTabbedPane1.getAccessibleContext().setAccessibleName("");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelarActionPerformed
        //Descarto los cambios hechos en las propiedades del Gestor de Configuración
        //y las vuelvo a cargar del fichero de propiedades
        GestorConfiguracion.getInstancia().load();
        setVisible(false);
    }//GEN-LAST:event_jButtonCancelarActionPerformed

    private void jButtonTestConexionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTestConexionActionPerformed
        //Actualizo las propiedades en el Gestor de Configuración
        this.pantallaAClase ();
        //Inicializo el vector global de errores
        GestorErrores.getInstancia().getvErrores().clear();
        //Pruebo los nuevos parámetros pero sin tocar la conexión actual
        if ( !GestorBD.getInstancia().testConexion() ){
            //Si ha habido errores informo de ellos
            String mensaje = "¡Error en la operación!" + "\n";
            for (int i= 0; i< GestorErrores.getInstancia().getvErrores().size(); i++)
                mensaje = mensaje + GestorErrores.getInstancia().getvErrores().get(i) + "\n";
            JOptionPane.showMessageDialog( null, mensaje,"Aviso", JOptionPane.WARNING_MESSAGE);
        }else{
            JOptionPane.showMessageDialog( null, "Conexión probada con éxito","Aviso", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_jButtonTestConexionActionPerformed

    private void jButtonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAceptarActionPerformed
        //Actualizo en el gestor de configuración
        this.pantallaAClase ();
        //Inicializo el vector global de errores
        GestorErrores.getInstancia().getvErrores().clear();
        //Grabo en el archivo de propiedades
        boolean bResultadoOK = GestorConfiguracion.getInstancia().update();
        //Reconecto con la Base de Datos con la nueva configuración
        bResultadoOK = bResultadoOK && GestorBD.getInstancia().cerrarConexion();
        bResultadoOK = bResultadoOK && GestorBD.getInstancia().abrirConexion();
        if ( !bResultadoOK ){
            //Si ha habido errores informo de ellos
            String mensaje = "¡Error en la operación!" + "\n";
            for (int i= 0; i< GestorErrores.getInstancia().getvErrores().size(); i++)
                mensaje = mensaje + GestorErrores.getInstancia().getvErrores().get(i) + "\n";
            JOptionPane.showMessageDialog( null, mensaje,"Aviso", JOptionPane.WARNING_MESSAGE);
        }else{
            JOptionPane.showMessageDialog( null, "Modificación realizada","Aviso", JOptionPane.INFORMATION_MESSAGE);
        }
        //Ocultar la ventana solo si el resultado ha sido OK.
        setVisible ( (bResultadoOK)? false:true );
    }//GEN-LAST:event_jButtonAceptarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAceptar;
    private javax.swing.JButton jButtonCancelar;
    private javax.swing.JButton jButtonTestConexion;
    private javax.swing.JFormattedTextField jFTFMaxAutorizAuto;
    private javax.swing.JFormattedTextField jFTFMinDenegAuto;
    private javax.swing.JFormattedTextField jFTFPuerto;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField jTFHost;
    private javax.swing.JTextField jTFNombreBD;
    private javax.swing.JTextField jTFPassword;
    private javax.swing.JTextField jTFUsuario;
    private javax.swing.JTabbedPane jTabbedPane1;
    // End of variables declaration//GEN-END:variables

}
